More Related Content Similar to computer notes - Data Structures - 38 (20) More from ecomputernotes (20) computer notes - Data Structures - 381. Class No.38 Data Structures http://ecomputernotes.com 3. Sorting Integers 20 8 5 10 7 5 7 8 10 20 How to sort the integers in this array? http://ecomputernotes.com 6. Selection Sort -- Example 1 2 3 0 7 12 19 5 a: 19 1 2 3 0 7 19 12 5 a: 12 1 2 3 0 19 7 12 5 a: 7 1 2 3 0 7 12 19 5 a: 1 2 3 0 5 7 12 19 a: a: 1 2 3 0 5 http://ecomputernotes.com 7. Selection Sort: Code void selectionSort(int *arr, int N) { int posmin, count, tmp; for(count=0;count<N;count++) { posmin = findIndexMin(arr,count,N); tmp=arr[posmin]; arr[posmin]=arr[count]; arr[count]=tmp; } } http://ecomputernotes.com 8. Selection Sort: Code int findIndexMin(int *arr, int start, int N) { int posmin=start; int index; for(index=start; index < N; index++) if (arr[index]<arr[posmin]) posmin=index; return posmin; } http://ecomputernotes.com 12. Insertion Sort -- Example 1 2 3 0 12 5 7 19 a : 1 2 3 0 19 5 7 12 a : 1 2 3 0 12 19 7 5 a : 1 2 3 0 7 12 19 5 a : http://ecomputernotes.com 13. Insertion Sort: Code void insertionSort(int *arr, int N) { int pos, count, val; for(count=1; count < N; count++) { val = arr[count]; for(pos=count-1; pos >= 0; pos--) if (arr[pos] > val) arr[pos+1]=arr[pos]; else break; arr[pos+1] = val; } } http://ecomputernotes.com 14. Insertion Sort -- animation 1 2 3 0 12 5 7 19 a : 1 2 3 0 19 5 7 19 a : count val pos 1 12 0 1 12 -1 1 2 3 0 5 7 19 a : 12 19 1 2 3 0 19 5 7 12 a : 12 http://ecomputernotes.com 15. Insertion Sort -- animation (cont) 1 2 3 0 12 19 7 5 a : count val pos 2 5 1 2 5 -1 1 2 3 0 19 5 7 12 a : 1 2 3 0 5 7 12 a : 19 19 1 2 3 0 19 7 12 a : 19 12 2 5 0 1 2 3 0 12 19 7 12 a : 5 http://ecomputernotes.com 16. Insertion Sort -- animation (cont) 1 2 3 0 12 19 7 5 a : count val pos 3 7 2 3 7 0 3 7 1 1 2 3 0 12 19 7 5 a : 19 1 2 3 0 12 19 19 5 a : 12 1 2 3 0 12 12 19 5 a : 7 1 2 3 0 7 12 19 5 a : http://ecomputernotes.com 19. Bubble Sort -- Example 1 2 3 0 12 7 19 5 a: 1 2 3 0 12 7 19 5 a: 19 12 7 5 1 2 3 0 a: 12 19 7 5 a: 1 2 3 0 5 12 7 19 1 2 3 0 a: a: 1 2 3 0 12 7 19 5 a: 1 2 3 0 7 12 19 5 a: 1 2 3 0 7 12 19 5 a: 1 2 3 0 7 12 19 5 a: 1 2 3 0 7 12 19 5 a: http://ecomputernotes.com 20. Bubble Sort: Code void bubbleSort(int *arr, int N){ int i, temp, bound = N-1; int swapped = 1; while (swapped > 0 ) { swapped = 0; for(i=0; I < bound; i++) if ( arr[i] > arr[i+1] ) { temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; swapped = i; } bound = swapped; } } http://ecomputernotes.com 24. Divide and Conquer What if we split the list into two parts? 10 12 8 4 2 11 7 5 10 12 8 4 2 11 7 5 http://ecomputernotes.com 25. Divide and Conquer Sort the two parts: 10 12 8 4 2 11 7 5 4 8 10 12 2 5 7 11 http://ecomputernotes.com 26. Divide and Conquer Then merge the two parts together: 4 8 10 12 2 5 7 11 2 4 5 7 8 10 11 12 http://ecomputernotes.com Editor's Notes End of lecture 43. Start of 44 End of lecture 44.